package com.taptech.doufu.ui.activity;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.luck.picture.lib.entity.LocalMedia;
import com.taptech.doufu.bean.base.BaseResponseBean;
import com.taptech.doufu.model.novel.bean.NovelSettingReviewBeanGson;
import com.taptech.doufu.net.retrofit.api.ApiClient;
import com.taptech.doufu.net.retrofit.api.BaseSubscriber;
import com.taptech.doufu.net.retrofit.api.RxJavaHelper;
import com.taptech.doufu.ui.activity.base.DiaobaoBaseActivity;
import com.taptech.doufu.ui.dialog.DoubleBtnTiptDialog;
import com.taptech.doufu.ui.dialog.SingleBtnDialog;
import com.taptech.doufu.bean.TagsBean;
import com.taptech.doufu.ui.view.WaitDialog;
import com.taptech.doufu.util.GlideUtil;
import com.taptech.doufu.util.TMAnalysis;
import com.taptech.doufu.util.TTLog;
import com.taptech.doufu.R;
import com.taptech.doufu.ui.activity.weex.SimpleWeexActivity;
import com.taptech.doufu.app.WeMediaApplication;
import com.taptech.doufu.bean.ImageBean;
import com.taptech.doufu.bean.MineNovelBean;
import com.taptech.doufu.constant.Constant;
import com.taptech.doufu.bean.TipInfo;
import com.taptech.doufu.listener.HttpResponseListener;
import com.taptech.doufu.listener.ResultTipListener;
import com.taptech.doufu.services.NovelCreateServices;
import com.taptech.doufu.services.MangerService;
import com.taptech.doufu.listener.UGCJSONObjectRet;
import com.taptech.doufu.services.UGCMainService;
import com.taptech.doufu.util.DiaobaoUtil;
import com.taptech.doufu.util.FileHashUtil;
import com.taptech.doufu.util.ImageManager;
import com.taptech.doufu.util.ScreenUtil;
import com.taptech.doufu.util.UIUtil;
import com.taptech.doufu.util.DiaobaoUtil.FileType;
import com.taptech.doufu.net.httputils.HttpResponseObject;
import com.taptech.doufu.util.image.ImagePickUtil;
import com.taptech.doufu.ui.view.ImageUtil;
import com.taptech.doufu.ui.view.NovelAptitudeDialog;
import com.taptech.doufu.ui.view.NovelModifiedStatusDialog;
import com.taptech.doufu.ui.view.NovelOriginalDialog;
import com.taptech.doufu.ui.view.NovelPublishDialog;
import com.taptech.doufu.ui.view.TipDialog;
import com.taptech.doufu.weex.notification.QLXNotificationCenter;
import com.taptech.doufu.weex.notification.QLXNotificationListener;
import com.taptech.doufu.ui.view.theme.ThemeType;
import com.taptech.doufu.ui.view.theme.read.ReadThemeHelper;

import static com.taptech.doufu.ui.activity.AddTagActivity.MESSAGE_TAG_BACK;

public class NovelCreateSetActivity extends DiaobaoBaseActivity implements HttpResponseListener, View.OnClickListener,
        NovelPublishDialog.PublishTypeSelectListener, NovelOriginalDialog.OriginalTypeSelectListener, NovelAptitudeDialog.AptitudeTypeSelectListener
{
    private final int SET_RESULT = 10;
    private TextView novelTags, novelDes, novelStatus, novelName,tvOutline,tvRecommendDesc,tvTipEnter;
    private ImageView ivVerticalCover,ivHorizontalCover,ivPreCollect;
    private RelativeLayout rlPublish, rlAptitude,layVerticalCover,layHorizontalCover;
    private HorizontalScrollView mScrollView;
    private TextView tvPublish, tvAptitude,tvSubmit;
    private LinearLayout llPreCollect;
    private MineNovelBean bean;
    public final static int NOVEL_NAME_RESULT = 10;
    public final static int NOVEL_DES_RESULT = 11;
    public final static int NOVEL_TAGS_RESULT = 12;
    public final static int NOVEL_RECOMMEND_DES_RESULT = 13;
    private Bitmap bitmap = null;
    private String hashValue = null;

    private int typePublishNum, typeOriginalNum, typeAptitudeNum;
    private String tongOriginal, aptitudeNameA, aptitudeNameB;

    private String peopleContent,storyContent;

    private ArrayList<String> customTags = new ArrayList<>();
    private HashMap<Integer, String> governmentTags = new HashMap<>();
    private final static int COVER_TYPE_VERTICAL = 1;
    private final static int COVER_TYPE_HORIZONTAL = 2;
    private int loadingCoverType = COVER_TYPE_HORIZONTAL;
    private ImageView ivPreCollectHelp;
    private View llRule;
    private WaitDialog waitDialog;
    private boolean dataChange;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_novel_create_set);
        initUI();
        Serializable serializable = getIntent().getSerializableExtra(Constant.DATA);

        if (serializable != null) {
            bean = (MineNovelBean) serializable;
            getNovelReview();
        }
    }

    private void initData() {
        setNovelStatus(bean.getFinished());
        setNovelDesStatus();
        setNovelRecommendDesStatus();
        novelName.setText(bean.getTitle());
        if (bean != null) {
            initTags(bean.getTags());
        }
        setNovelPic();
        setData();
        setOutlineState();
        setNovelTagStatus();
        setPreCollectView();
        QLXNotificationCenter.getInstance().addNotify("workOnlineChange", this, new QLXNotificationListener() {
            @Override
            public void notify(String event, Object data) {
                try {
                    dataChange = true;
                    com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(data.toString());
                    if (jsonObject.containsKey("outline")) {
                        storyContent = jsonObject.getString("outline");

                    }
                    if (jsonObject.containsKey("peopleContent")) {
                        peopleContent = jsonObject.getString("peopleContent");
                    }
                    if (bean != null) {
                        bean.setOutline(storyContent);
                        bean.setPeople_setup(peopleContent);
                    }
                    setOutlineState();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }


    private void getNovelReview() {
        ApiClient.getInstance().getService().getNovelSettingReview(Integer.parseInt(bean.getId()))
                .compose(RxJavaHelper.observeOnMainThread(this))
                .subscribe(new BaseSubscriber<BaseResponseBean<NovelSettingReviewBeanGson>>(){
                    @Override
                    public void onNext(BaseResponseBean<NovelSettingReviewBeanGson> b) {
                        super.onNext(b);
                        if (b != null && b.getData() != null) {
                            NovelSettingReviewBeanGson gson = b.getData();
                            if (gson.getDescription()!=null && gson.getDescription().getNew_val()!=null && !gson.getDescription().getNew_val().isEmpty()){
                                bean.setDes(gson.getDescription().getNew_val());
                            }

                            if (gson.getOutline()!=null && gson.getOutline().getNew_val()!=null && !gson.getOutline().getNew_val().isEmpty()){
                                bean.setOutline(gson.getOutline().getNew_val());
                            }

                            if (gson.getPeople_setup()!=null && gson.getPeople_setup().getNew_val()!=null && !gson.getPeople_setup().getNew_val().isEmpty()){
                                bean.setPeople_setup(gson.getPeople_setup().getNew_val());
                            }

                            if (gson.getTopic_title()!=null && gson.getTopic_title().getNew_val()!=null && !gson.getTopic_title().getNew_val().isEmpty()){
                                bean.setTitle(gson.getTopic_title().getNew_val());
                            }

                            if (gson.getNovel_tags()!=null && gson.getNovel_tags().getTags()!=null && gson.getNovel_tags().getTags().size()>0){
                                bean.setTags(gson.getNovel_tags().getTags().toArray(new TagsBean[gson.getNovel_tags().getTags().size()]));
                            }

                            if (gson.getRecommend_text() != null && gson.getRecommend_text().getNew_val() != null && !gson.getRecommend_text().getNew_val().isEmpty()) {
                                bean.setDescription2(gson.getRecommend_text().getNew_val());
                            }

                            if (gson.getWith_image_w() != null && gson.getWith_image_w().getNew_val() != null && !gson.getWith_image_w().getNew_val().isEmpty()) {
                                bean.setWith_image_w(gson.getWith_image_w().getNew_val());
                            }
                        }
                        initData();
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        initData();
                    }
                });
    }


    private void initTags(TagsBean[] tags) {
        try {
            if (tags != null && tags.length > 0) {
                for (TagsBean bean:tags) {
                    int type = Integer.parseInt(bean.getTag_type());
                    if (type > 0) {
                        governmentTags.put(type, bean.getName());
                    }else{
                        customTags.add(bean.getName());
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void initUI() {
        tvTipEnter = findViewById(R.id.tvTipEnter);
        tvTipEnter.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
        tvTipEnter.setOnClickListener(v -> {
            BrowseActivity.startActivity(getThisActivity(),"https://api.douhuawenxue.com/journal/detail?id=833");
        });
        ivPreCollectHelp = (ImageView) findViewById(R.id.ivPreCollectHelp);
        llRule = findViewById(R.id.llRule);
        tvOutline = (TextView) findViewById(R.id.tvOutline);
        novelTags = (TextView) findViewById(R.id.activity_create_set_tags);
        novelDes = (TextView) findViewById(R.id.activity_create_set_des);
        tvRecommendDesc = (TextView) findViewById(R.id.tvRecommendDesc);
        novelStatus = (TextView) findViewById(R.id.activity_novel_set_tv_status);
        novelName = (TextView) findViewById(R.id.activity_set_novel_name);
        rlPublish = (RelativeLayout) findViewById(R.id.rl_activity_novel_create_tos_publish);
        rlPublish.setOnClickListener(this);
        rlAptitude = (RelativeLayout) findViewById(R.id.rl_activity_novel_create_tos_aptitude);
        rlAptitude.setOnClickListener(this);
        tvAptitude = (TextView) findViewById(R.id.tv_activity_novel_create_tos_aptitude);
        tvSubmit = (TextView) findViewById(R.id.tvSubmit);
        tvSubmit.setOnClickListener(this);
        tvPublish = (TextView) findViewById(R.id.tv_activity_novel_create_tos_publish);
        mScrollView = (HorizontalScrollView) findViewById(R.id.mScrollView);
        layHorizontalCover = (RelativeLayout) findViewById(R.id.layHorizontalCover);
        ivHorizontalCover = (ImageView) findViewById(R.id.ivHorizontalCover);
        ivVerticalCover = (ImageView) findViewById(R.id.ivVerticalCover);
        layHorizontalCover.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mScrollView.fullScroll(ScrollView.FOCUS_RIGHT);

            }
        });
        layVerticalCover = (RelativeLayout) findViewById(R.id.layVerticalCover);
        layVerticalCover.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mScrollView.fullScroll(ScrollView.FOCUS_LEFT);
                showPhotoDialog(COVER_TYPE_VERTICAL);

            }
        });
        llPreCollect = (LinearLayout) findViewById(R.id.llPreCollect);
        ivPreCollect = (ImageView) findViewById(R.id.ivPreCollect);
        ivPreCollect.setOnClickListener(this);
        ivPreCollectHelp.setOnClickListener(this);
        llRule.setOnClickListener(this);
    }

    private void showPhotoDialog(final int loadingCoverType) {
        this.loadingCoverType = loadingCoverType;
        final BottomSheetDialog dialog = new BottomSheetDialog(this);
        dialog.setContentView(R.layout.dialog_take_photo);
        LinearLayout layUpload = dialog.findViewById(R.id.layUpload);
        LinearLayout layRule = dialog.findViewById(R.id.layRule);
        LinearLayout layCoverRule = dialog.findViewById(R.id.layCoverRule);
        LinearLayout layCancel = dialog.findViewById(R.id.layCancel);
        TextView tvUpload = dialog.findViewById(R.id.tvUpload);
        TextView tvDesc = dialog.findViewById(R.id.tvDesc);
        TextView tvCoverRule = dialog.findViewById(R.id.tvCoverRule);
        tvCoverRule.getPaint().setFlags(Paint. UNDERLINE_TEXT_FLAG );
        if (loadingCoverType == COVER_TYPE_HORIZONTAL) {
            tvUpload.setText("点击上传横版封面");
            tvDesc.setText("(建议上传800*400px尺寸图片)");
            layUpload.setVisibility(View.GONE);
        }else{
            tvUpload.setText("点击上传竖版封面");
            tvDesc.setText("（建议上传600*800px尺寸图片）");
            layUpload.setVisibility(View.VISIBLE);
        }
        layCancel.setOnClickListener(v -> dialog.dismiss());
        layUpload.setOnClickListener(v -> {
            editPicOnclick(loadingCoverType);
            dialog.dismiss();
        });
        layCoverRule.setOnClickListener(v->{
            dialog.dismiss();
            Intent intent = new Intent();
            intent.setClass(NovelCreateSetActivity.this, BrowseActivity.class);
            intent.putExtra(Constant.URL, "https://api.douhuawenxue.com/journal/detail?id=832");
            intent.putExtra(Constant.TITLE, "");
            startActivity(intent);
        });
        layRule.setOnClickListener(v -> {
            dialog.dismiss();
            Intent intent = new Intent();
            intent.setClass(NovelCreateSetActivity.this, BrowseActivity.class);
            intent.putExtra(Constant.URL, "https://api.douhuawenxue.com/journal/detail?id=831");
            intent.putExtra(Constant.TITLE, "");
            startActivity(intent);
        });
        dialog.show();
    }

    private void setData(){
        if (bean != null) {
            peopleContent = bean.getPeople_setup();
            storyContent = bean.getOutline();
        }
        if(!TextUtils.isEmpty(bean.getPublish_type())){
            typePublishNum = Integer.valueOf(bean.getPublish_type());
            switch (typePublishNum){
                case 1:
                    tvPublish.setText("驻站");
                    break;
                case 2:
                    tvPublish.setText("首发");
                    break;
                case 3:
                    tvPublish.setText("独家");
                    break;
                default:
                    break;
            }
        }
        if(!TextUtils.isEmpty(bean.getIs_original())){
            typeOriginalNum = Integer.valueOf(bean.getIs_original());
            tongOriginal = bean.getNovel_source();
        }
        if(!TextUtils.isEmpty(bean.getSexual())){
            typeAptitudeNum = Integer.valueOf(bean.getSexual());
            aptitudeNameA = bean.getSexual_name1();
            aptitudeNameB = bean.getSexual_name2();
            tvAptitude.setText(getAptitudeName(typeAptitudeNum));
        }
    }

    public void modifiedNameOnclick(View view)
    {
        if (bean != null)
        {
            Intent intent = new Intent(this, NovelModifiedNameActivity.class);
            intent.putExtra(Constant.ARTICLE_ID, bean.getId());
            intent.putExtra(Constant.ARTICLE_TITLE, bean.getTitle());
            startActivityForResult(intent, SET_RESULT);
        }

    }

    public void editPicOnclick(int loadingCoverType) {
        if (loadingCoverType == COVER_TYPE_HORIZONTAL) {
            ImagePickUtil.pickImage(this, 1, true, 0, 750, 375, ScreenUtil.getScreenWidth(this),ScreenUtil.getScreenWidth(this)/2,new ImagePickUtil.OnPickImageListen() {
                @Override
                public void onPickImage(List<LocalMedia> paths) {
                    if (paths != null && paths.size() > 0) {
                        LocalMedia item= paths.get(0);
                        if (item!=null){
                            if (item.isCut()) {
                                bitmap = BitmapFactory.decodeFile(item.getCutPath());
                            }else{
                                bitmap = BitmapFactory.decodeFile(item.getRealPath());
                            }
                            showWaitDialog();
                            bitmap = ImageManager.setPicToView(bitmap, ret);
                        }
                    }
                }
            });
        }else{
            ImagePickUtil.pickImage(this, 1, true, 0, 600, 800, 600,800,new ImagePickUtil.OnPickImageListen() {
                @Override
                public void onPickImage(List<LocalMedia> paths) {
                    if (paths != null && paths.size() > 0) {
                        LocalMedia item= paths.get(0);
                        if (item!=null){
                            if (item.isCut()) {
                                bitmap = BitmapFactory.decodeFile(item.getCutPath());
                            }else{
                                bitmap = BitmapFactory.decodeFile(item.getRealPath());
                            }
                            showWaitDialog();
                            bitmap = ImageManager.setPicToView(bitmap, ret);
                        }
                    }
                }
            });
        }

    }


    public void tagsOnclick(View view) {
        TMAnalysis.event(this, "novel_set_click_tags");
        if (bean == null) 
            return;
        Intent intent = new Intent(this, TagSelectActivity.class);
        intent.putExtra(TagSelectActivity.INTENT_KEY_TOPIC_ID, bean.getId());
        intent.putExtra(TagSelectActivity.INTENT_KEY_GOVERMENT_TAG, governmentTags);
        intent.putExtra(TagSelectActivity.INTENT_KEY_CUSTOM_TAG, customTags);
        intent.putExtra(TagSelectActivity.INTENT_KEY_SEXUALITY, bean.getSexual());
        startActivityForResult(intent, SET_RESULT);

    }

    public void desOnclick(View view)
    {
        if (bean != null)
        {
            Intent intent = new Intent(NovelCreateSetActivity.this, NovelModifiedDesActivity.class);
            intent.putExtra(Constant.ARTICLE_ID, bean.getId());
            intent.putExtra(Constant.DESC, bean.getDes());
            startActivityForResult(intent, SET_RESULT);
        }

    }

    public void recommendDesOnclick(View view) {
        if (bean != null)
        {
            Intent intent = new Intent(NovelCreateSetActivity.this, NovelModifiedRecommendDesActivity.class);
            intent.putExtra(Constant.ARTICLE_ID, bean.getId());
            intent.putExtra(Constant.DESC, bean.getDescription2());
            startActivityForResult(intent, SET_RESULT);
        }
    }


    public void outlineOnclick(View view) {
        HashMap<String, String> params = new HashMap<>();
        params.put("peopleContent",peopleContent);
        params.put("storyContent", storyContent);
        if (bean != null) {
            params.put("novelID", bean.getId());
        }
        SimpleWeexActivity.startActivity(this,"TFNovel/outlineView.js",params);
    }


    private void setOutlineState() {
        if (TextUtils.isEmpty(peopleContent) && TextUtils.isEmpty(storyContent)) {
            tvOutline.setText("请设置（必填）");
            if(WeMediaApplication.getInstance().isDayNightMode_Night){
                tvOutline.setTextColor(getResources().getColor(R.color.theme_main_dark));
            }else {
                tvOutline.setTextColor(getResources().getColor(R.color.text_color_67));
            }

        }else{
            tvOutline.setText("已设置");
            tvOutline.setTextColor(Color.parseColor("#999999"));

        }
    }

    public void novelStatusOnclick(View view)
    {
        if (isNullBean())
        {
            return;
        }
        NovelModifiedStatusDialog dialog = new NovelModifiedStatusDialog(this, R.style.updateDialog, isFinishNovel(), bean.getId(), handler);
        dialog.show();
    }

    public void delOnclick(View view)
    {
        TipInfo info = new TipInfo();
        info.setTipContent("是否删除小说");
        info.setTipListener(tipListener);
        TipDialog dialog = new TipDialog(this, R.style.updateDialog, info);
        dialog.show();

    }

    private Handler handler = new Handler()
    {
        @Override
        public void handleMessage(Message msg)
        {
            // TODO Auto-generated method stub
            super.handleMessage(msg);
            if (isNullBean())
            {
                return;
            }
            String finished = getFinished(msg.what);
            bean.setFinished(finished);
            setNovelStatus(bean.getFinished());
        }
    };

    private String getFinished(int what)
    {
        String finished = "0";
        if (what == 1)
        {
            finished = "1";
        } else
        {
            finished = "0";
        }
        return finished;
    }

    private void setNovelStatus(String finishFlag)
    {
        if ("1".equals(finishFlag))
        {
            novelStatus.setText("完结文");
        } else
        {
            novelStatus.setText("连载中");
        }
    }

    private void setNovelDesStatus()
    {
        if (bean.getDes() != null && !"".equals(bean.getDes()))
        {
            novelDes.setText(bean.getDes());
            novelDes.setTextColor(Color.parseColor("#999999"));

        } else
        {
            novelDes.setText("请设置（必填）");
            if(WeMediaApplication.getInstance().isDayNightMode_Night){
                novelDes.setTextColor(getResources().getColor(R.color.theme_main_dark));
            }else {
                novelDes.setTextColor(getResources().getColor(R.color.text_color_67));
            }
        }
    }


    private void setNovelRecommendDesStatus()
    {
        if (bean.getDescription2() != null && !"".equals(bean.getDescription2()))
        {
            tvRecommendDesc.setText(bean.getDescription2());
            tvRecommendDesc.setTextColor(Color.parseColor("#999999"));

        } else
        {
            tvRecommendDesc.setText("请设置（必填）");
            if(WeMediaApplication.getInstance().isDayNightMode_Night){
                tvRecommendDesc.setTextColor(getResources().getColor(R.color.theme_main_dark));
            }else {
                tvRecommendDesc.setTextColor(getResources().getColor(R.color.text_color_67));
            }
        }
    }

    private String getStrTags() {
        StringBuilder sb = new StringBuilder();
        if (governmentTags != null && governmentTags.values()!=null) {

            for (String tag: governmentTags.values()) {
                sb.append(tag).append("-");
            }
        }
        if (customTags != null) {
            for (int i = 0; i < customTags.size(); i++)
            {
                sb.append(customTags.get(i)).append("-");
            }
        }
        String str = "";
        if (sb.length() > 0) {
            str = sb.substring(0,sb.length()-1);
        }
        return str;
    }

    private void setPreCollectView() {
        //判断是否为已发布作品
        if ("0".equals(bean.getArticle_num())) {
            llPreCollect.setVisibility(View.VISIBLE);
        }else{
            llPreCollect.setVisibility(View.GONE);
        }
        setPreCollectBtn();
    }

    private void setPreCollectBtn() {
        if (ReadThemeHelper.getReadTheme().getThemeType() == ThemeType.TYPE_NIGHT) {
            //夜间
            if ("1".equals(bean.getPre_collect())) {
                ivPreCollect.setImageResource(R.drawable.read_switch_o_night);
            }else{
                ivPreCollect.setImageResource(R.drawable.read_switch_c_night);
            }
        }else{
            if ("1".equals(bean.getPre_collect())) {
                ivPreCollect.setImageResource(R.drawable.read_switch_o);
            }else{
                ivPreCollect.setImageResource(R.drawable.read_switch_c);
            }
        }
    }

    private void setNovelTagStatus()
    {
        if (governmentTags != null && governmentTags.values()!=null)
        {
            novelTags.setText(getStrTags());
            novelTags.setTextColor(Color.parseColor("#999999"));
        } else
        {
            novelTags.setText("请设置（必填）");
            if(WeMediaApplication.getInstance().isDayNightMode_Night){
                novelTags.setTextColor(getResources().getColor(R.color.theme_main_dark));
            }else {
                novelTags.setTextColor(getResources().getColor(R.color.text_color_67));
            }
        }
    }

    private void setNovelPic()
    {
        if (bean.getImages() != null && bean.getImages().length > 0) {
            GlideUtil.displayRoundImage(ivHorizontalCover, bean.getImages()[0].getImgUrl(),8);
        }

        if (!TextUtils.isEmpty(bean.getWith_image_w())) {
            GlideUtil.displayRoundImage(ivVerticalCover, bean.getWith_image_w(),8);
        }
    }

    private boolean isNullBean()
    {
        return bean == null;
    }

    private boolean isFinishNovel()
    {
        return isNullBean() ? false : "1".equals(bean.getFinished());
    }

    public void back(View view)
    {
        if (dataChange) {
            showSubmitTipDialog();
        }else{
            setResultData();
            finish();
        }
    }

    private void showWaitDialog() {
        if (waitDialog == null){
            waitDialog = new WaitDialog(this,R.style.updateDialog);
        }
        if (!waitDialog.isShowing()){
            waitDialog.show();
        }
    }

    private void dismissWaitDialog() {
        if (waitDialog != null && waitDialog.isShowing()) {
            waitDialog.dismiss();
        }
    }

    private ResultTipListener tipListener = new ResultTipListener()
    {

        @Override
        public void resultBack(int flag, int type)
        {
            // TODO Auto-generated method stub
            if (flag == 1 && bean != null)
            {
                MangerService.getInstance().mangerDelTopic(bean.getId(), NovelCreateSetActivity.this);
            }
        }
    };


    private void showSubmitTipDialog() {

        DoubleBtnTiptDialog doubleBtnLongTextDialog = new DoubleBtnTiptDialog(this,
                R.style.updateDialog, "提示","是否将更新的信息“提交审核”，信息“审核通过”后即可公开展示。\n" +
                "如选择“返回”，后续可点击该页面右上角手动“提交审核”", "返回","提交审核",
                ()->{
                    setResultData();
                    finish();
                },
                () -> {
                    NovelCreateServices.getInstance().submitNovelSet(this,bean.getId());
                    dataChange = false;
                    setResultData();
                    finish();
                });
        doubleBtnLongTextDialog.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {

        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);

        Log.d("tag", "=========requestCode is " + requestCode);
        Log.d("tag", "=========resultCode is " + resultCode);
        if (resultCode == RESULT_OK)
        {
            Log.d("tag", "start image get image");
            switch (requestCode)
            {
                // 如果是直接从相册获取
                case 1:
                    if (data != null)

                        ImageManager.startPhotoZoom(data.getData(), NovelCreateSetActivity.this, 750, 375);
                    // ImageManager.startPhotoZoom(data.getData(),NovelCreateSetActivity.this);
                    Log.d("tag", "start image gallery");
                    break;
                // 如果是调用相机拍照时
                case 2:
                    File temp = new File(Environment.getExternalStorageDirectory() + "/xiaoma.jpg");
                    ImageManager.startPhotoZoom(Uri.fromFile(temp), NovelCreateSetActivity.this, 750, 375);
                    Log.d("tag", "start image photo");
                    break;
                // 取得裁剪后的图片
                case 3:
                    /**
                     * 非空判断大家一定要验证，如果不验证的话， 在剪裁之后如果发现不满意，要重新裁剪，丢弃
                     * 当前功能时，会报NullException，小马只 在这个地方加下，大家可以根据不同情况在合适的 地方做判断处理类似情况
                     *
                     */
                    System.out.println("uri===========" + data);
                    if (data != null)
                    {
                        System.out.println("uri===========" + data.getData());
                        bitmap = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory() + "/Doufu/cutpic.jpg");
                        showWaitDialog();
                        bitmap = ImageManager.setPicToView(bitmap, ret);
                        Log.d("tag", "start image photoZoom");
                    }
                    break;

                default:
                    break;
            }
        }
        switch (resultCode)
        {
            case NOVEL_NAME_RESULT:
                if (data != null)
                {
                    String article_title = data.getStringExtra(Constant.ARTICLE_TITLE);
                    bean.setTitle(article_title);
                    novelName.setText(article_title);
                    dataChange = true;
                }

                break;
            case NOVEL_DES_RESULT:
                if (data != null)
                {
                    String des = data.getStringExtra(Constant.DESC);
                    bean.setDes(des);
                    setNovelDesStatus();
                    dataChange = true;
                }

                break;
            case NOVEL_RECOMMEND_DES_RESULT:
                if (data != null)
                {
                    String des = data.getStringExtra(Constant.DESC);
                    bean.setDescription2(des);
                    setNovelRecommendDesStatus();
                    dataChange = true;
                }

                break;
            case NOVEL_TAGS_RESULT:
                if (data != null) {
                    Serializable serializable = data.getSerializableExtra(TagSelectActivity.INTENT_KEY_ALL_TAGS);
                    if (serializable != null) {
                        try {
                            TagsBean[] tags = null;
                            if (serializable instanceof TagsBean[]){
                                tags = (TagsBean[]) serializable;
                            }else if (serializable instanceof Object[]){  //4.4及以下的版本
                                Object[] objs = (Object[]) serializable;
                                if (objs != null && objs.length > 0) {
                                    tags = new TagsBean[objs.length];
                                    for (int i=0;i<objs.length;i++){
                                        Object item = objs[i];
                                        if (item instanceof TagsBean){
                                            tags[i] = (TagsBean) item;
                                        }
                                    }
                                }

                            }
                            if (tags != null) {
                                bean.setTags(tags);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    governmentTags = (HashMap<Integer, String>) data.getSerializableExtra(TagSelectActivity.INTENT_KEY_GOVERMENT_TAG);
                    customTags = data.getStringArrayListExtra(TagSelectActivity.INTENT_KEY_CUSTOM_TAG);
                    setNovelTagStatus();
                }
                dataChange = true;
                break;
            case MESSAGE_TAG_BACK:
                break;
            default:
                break;
        }

    }

    private UGCJSONObjectRet ret = new UGCJSONObjectRet()
    {
        @Override
        public void onFailure(Exception ex)
        {
            ex.printStackTrace();
            UIUtil.toastMessage(NovelCreateSetActivity.this, "图片上传失败，请重试...");
            // bar.setVisibility(View.GONE);
        }

        @Override
        public void onPause(Object tag)
        {
            TTLog.s("onPause===========");
        }

        @Override
        public void onSuccess()
        {
            TTLog.s("onSuccess===========");
            if (bitmap == null || bean == null)
            {
                return;
            }
            byte[] datas = ImageUtil.Bitmap2Bytes(bitmap);
            hashValue = FileHashUtil.getDiabaoFileSHA384(datas, FileType.PNG);
            if (loadingCoverType == COVER_TYPE_HORIZONTAL) {
                GlideUtil.displayRoundImage(ivHorizontalCover, datas, 8);
                ImageBean imageBean = new ImageBean();
                imageBean.setPath(Constant.DIAOBAO_IMAGE_HOST + hashValue);
                imageBean.setImgUrl(Constant.DIAOBAO_IMAGE_HOST + hashValue);
                Map<String, String> imgMap = new HashMap<String, String>();
                imgMap.put("path", Constant.DIAOBAO_IMAGE_HOST + hashValue);
                imgMap.put("width", 800 + "");
                imgMap.put("height", 400 + "");
                JSONObject imgJsonObject = new JSONObject(imgMap);
                if (bean.getImages() != null && bean.getImages().length > 0) {
                    bean.getImages()[0] = imageBean;
                } else {
                    ImageBean[] imageBeans = new ImageBean[1];
                    imageBeans[0] = imageBean;
                    bean.setImages(imageBeans);
                }
                NovelCreateServices.getInstance().saveTopicNovel(NovelCreateSetActivity.this, bean.getId(), null, imgJsonObject.toString(), null, null, null,false);
            }else{
                Map<String, Object> imgMap = new HashMap<>();
                imgMap.put("path",  Constant.DIAOBAO_IMAGE_HOST + hashValue);
                imgMap.put("width", 600);
                imgMap.put("height", 800);
                JSONObject imgJsonObject = new JSONObject(imgMap);
                NovelCreateServices.getInstance().saveTopicNovel(NovelCreateSetActivity.this, bean.getId(), null, imgJsonObject.toString(), null, null, null,true);
            }
        }
    };

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        if (keyCode == event.KEYCODE_BACK) {
            if (dataChange){
                showSubmitTipDialog();
                return true;
            }
            setResultData();
        }
        return super.onKeyDown(keyCode, event);
    }

    private void setResultData()
    {
        if(bean != null){
            setResult(NewNovelCreateListTosActivity.RESULT_NOVEL_SET, getIntent().putExtra(Constant.DATA, bean));
        }
    }

    @Override
    public void handleResponse(int handleType, HttpResponseObject response)
    {
        // TODO Auto-generated method stub
        switch (handleType)
        {
            case NovelCreateServices.HANDLE_TYPE_SAVE_TOPIC_NOVEL:
                dismissWaitDialog();
                try {
                    if (response.getStatus() == 0){
                        UIUtil.toastMessage(this, "上传成功");
                        byte[] datas = ImageUtil.Bitmap2Bytes(bitmap);
                        GlideUtil.displayRoundImage(ivVerticalCover, datas, 8);
                        bean.setWith_image_w(Constant.DIAOBAO_IMAGE_HOST + hashValue);
                        dataChange = true;
                    }else{
                        String msg = response.getUser_msg();
                        if (msg != null && !TextUtils.isEmpty(msg)){
                            UIUtil.toastMessage(this, msg);
                        }else{
                            UIUtil.toastMessage(this, "上传失败");
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    UIUtil.toastMessage(this, "上传失败");
                }
                break;
            case MangerService.HANDLE_TYPE_MANGER_DEL:
                if (DiaobaoUtil.isRequestResult(response))
                {
                    UIUtil.toastMessage(this, "删除成功");
                    setResult(NewNovelCreateListTosActivity.RESULT_DEL_NOVEL);
                    finish();
                } else
                {
                    UIUtil.toastMessage(this, DiaobaoUtil.getErrorTips(response));
                }
                break;
            case NovelCreateServices.HANDLE_TYPE_PRE_COLLECT:
                if (DiaobaoUtil.isRequestResult(response)){
                    if ("1".equals(bean.getPre_collect())) {
                        bean.setPre_collect("0");
                        bean.setPre_collect_count(bean.getPre_collect_count()+1);
                    }else{
                        bean.setPre_collect("1");
                        bean.setPre_collect_count(bean.getPre_collect_count()-1);
                    }
                    setPreCollectBtn();
                }else{
                    Toast.makeText(NovelCreateSetActivity.this,"修改失败，请重试",Toast.LENGTH_LONG).show();
                }
                break;
            case NovelCreateServices.HANDLE_TYPE_SET_SUBMIT:
                if (DiaobaoUtil.isRequestResult(response)){
                    try {
                        String msg = ((JSONObject)response.getData()).getString("submitted_msg");
                        UIUtil.toastMessage(this, msg);
                    } catch (Exception e) {
                        e.printStackTrace();
                        UIUtil.toastMessage(this, "提交失败");
                    }
                }else{
                    UIUtil.toastMessage(this, "提交失败");
                }
                break;
            default:
                break;
        }

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.tvSubmit:
                NovelCreateServices.getInstance().submitNovelSet(this,bean.getId());
                dataChange = false;
                break;
            case R.id.llRule:
                BrowseActivity.startActivity(this,"https://api.douhuawenxue.com/journal/detail?id=833");
                break;
            case R.id.ivPreCollectHelp:
                SingleBtnDialog singleBtnDialog = new SingleBtnDialog(this, R.style.updateDialog,
                        "作品的“预收藏”功能类似于作品的预发布功能，作者可以先创作文章名、简介等信息，暂不发表正文，读者可收藏、分享；“预收藏”功能是作者预热作品的小工具，具体有以下规则：\n" +
                                "1、作者在新建作品时可以设置自己的作品为“预收藏”作品；\n" +
                                "2、每个作者最多只能同时设置2部作品为“预收藏”状态；\n" +
                                "3、设置了“预收藏”的作品将在作者的个人主页默认置顶；\n" +
                                "4、作品任意一章点击”发布“后，作品的预收藏状态将自动取消；\n" +
                                "5、如作品已发布或任意章节、不管章节是否通过，都不能设置预收藏。", "关于“预收藏”功能","好的");
                singleBtnDialog.show();
                break;
            case R.id.rl_activity_novel_create_tos_publish:
                NovelPublishDialog dialogPublish = new NovelPublishDialog(this, R.style.UgcSweepDialog, typePublishNum, bean, 3);
                dialogPublish.setOnPublishTypeSeleceListener(this);
                setDialogAttribute(dialogPublish);
                break;
            case R.id.rl_activity_novel_create_tos_aptitude:
                Toast.makeText(NovelCreateSetActivity.this,"\"性向\"不支持修改，如需修改请联系编辑，谢谢！",Toast.LENGTH_LONG).show();
                break;
            case R.id.ivPreCollect:
                if ("1".equals(bean.getPre_collect())){
                    //取消预收藏
                    NovelCreateServices.getInstance().saveNovelPreCollect(this,bean.getId(),0);

                }else{
                    //预收藏余额不足
                    if (bean.getPre_collect_count() <= 0) {
                        Toast.makeText(NovelCreateSetActivity.this,"预收藏作品额度已滿",Toast.LENGTH_LONG).show();
                        break;
                    }
                    //简介不足100字时
                    if (bean.getDes().length() < 100) {
                        Toast.makeText(NovelCreateSetActivity.this,"请先填写简介滿100字",Toast.LENGTH_LONG).show();
                        break;
                    }
                    NovelCreateServices.getInstance().saveNovelPreCollect(this,bean.getId(),1);

                }
                break;
            default:
                break;
        }
    }

    private void setDialogAttribute(Dialog dialog){
        dialog.show();
        android.view.WindowManager.LayoutParams lp = dialog.getWindow().getAttributes();
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = WindowManager.LayoutParams.MATCH_PARENT;
        dialog.getWindow().setAttributes(lp);
    }

    @Override
    public void selectAptitudeTwoListener(String typeAptitudeOne, String typeAptitudeTwo, int typeNum) {
        tvAptitude.setText(getAptitudeName(typeNum));
        typeAptitudeNum = typeNum;
        aptitudeNameA = null;
        aptitudeNameB = null;
        aptitudeNameA = typeAptitudeOne;
        aptitudeNameB = typeAptitudeTwo;
        bean.setSexual(String.valueOf(typeNum));
        bean.setSexual_name1(aptitudeNameA);
        bean.setSexual_name2(aptitudeNameB);
    }

    @Override
    public void selectOriginalListener(String typeOriginal, int typeNum, String tongOrihinal) {
        typeOriginalNum = typeNum;
        this.tongOriginal = null;
        this.tongOriginal = tongOrihinal;
        bean.setIs_original(String.valueOf(typeNum));
        bean.setNovel_source(this.tongOriginal);
    }

    @Override
    public void selectListener(String typeName, int typeNum) {
        tvPublish.setText(typeName);
        typePublishNum = typeNum;
        bean.setPublish_type(String.valueOf(typeNum));
    }

    private String getAptitudeName(int typeNum){
        if(1 == typeNum){
            return "彩虹/BL";
        }else if(2 == typeNum){
            return "百合/GL";
        }else if(3 == typeNum){
            return "言情/BG";
        }else if(4 == typeNum){
            return "女尊/GB";
        }else{
            return "无CP、无性向";
        }
    }
}
